<?php
/**
 * UserController class file.
 *
 * @package   controllers
 * @since     1.0
 * @filesource
 */

/**
 * Controller for user. Contains action to manage user for admin, and allow user to change password.
 * Controller class is also responsible for rendering page.
 */
class UserController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @var string the name of the default action. In this case, admin is the default action, meaning
	 * when request the controller not specifying the action, the action that will be called.
	 */
	public $defaultAction='admin';

	/**
	 * Return a list of filters that will be used to control access.
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter which is declared in $this->filters().
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // only allow admin to perform management actions
					'actions'=>array('admin','create','update','delete','changeUserPassword'),
					'roles'=>array('admin'),
			),
			array('allow',  // allow any user change his own password
					'actions'=>array('changePassword'),
					'users'=>array('@'),
			),
			array('deny',  // deny all other users
					'users'=>array('*'),
			),
		);
	}

	/**
	 * Creates a new user.
	 * This action will display a form for creating a user if no data posted back.
	 * If data posted back, it will validate the data and try to save it to database.
	 * If creation is successful, the browser will be redirected to the 'admin' page.
	 */
	public function actionCreate()
	{
		$model=new User;
		$this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			$model->username=trim($model->username);//Make sure username is unique.
			if($model->save())
				$this->redirect(array('admin'));
		}else{
			// set the value of global access on Creation page according the admin's setting.
			$model->globalCreate=GlobalConfiguration::getByKey('NEW_USER_ACCESS_CREATE');
			$model->globalDelete=GlobalConfiguration::getByKey('NEW_USER_ACCESS_DELETE');
			$model->globalDownload=GlobalConfiguration::getByKey('NEW_USER_ACCESS_DOWNLOAD');
			$model->globalUpdate=GlobalConfiguration::getByKey('NEW_USER_ACCESS_UPDATE');
			$model->globalView=GlobalConfiguration::getByKey('NEW_USER_ACCESS_VIEW');
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular user.
	 * This action will display a form for updating a user if no data posted back.
	 * If data posted back, it will validate the data and try to save it to database.
	 * If update is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the user to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		$this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			if($model->save())
				$this->redirect(array('admin'));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular user.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the user to be deleted
	 * @throws CHttpException If the request is not POST request
	 * @throws CHttpException If admin want to delete his account.
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			if ($id==Yii::app()->user->id) {
				// Avoid admin delete himself.
				throw new CHttpException(400,'Invalid request. Please Do Not Kill Yourself.');
			}
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Manages all users of one or all organization.
	 * This action will render an admin page with model class User's method search() to produce a list of users.
	 * This method will produce a list of users by search conditions.
	 * @param integer id of organization to which the users belonges.
	 */
	public function actionAdmin($organizationId=null)
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];

		$organization=$organizationId?Organization::model()->findByPk($organizationId):null;
		
		$this->render('admin',array(
			'model'=>$model,
			'organization'=>$organization,
		));
	}

	/**
	 * Returns the User object based on the primary key given in the GET variable.
	 * @param integer the ID of the model to be loaded
	 * @return User an User object with given id.
	 * @throws CHttpException If the User object is not found
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	
	/**
	 * Action to allow user to changes his own password.
	 * If the changes is successful, the browser will be redirected to index page of the site.
	 */
	public function actionChangePassword()
	{
		$model=new ChangePasswordForm();
		
	    if(isset($_POST['ChangePasswordForm']))
	    {
	        $model->attributes=$_POST['ChangePasswordForm'];
	        if($model->validate())
	        {
	            // form inputs are valid, then update user's password in database.
	            $user=$this->loadModel(Yii::app()->user->id);
	            $user->password=hash('sha512', $user->username.$model->newPassword);
				if($user->save())
					$this->redirect(array('site/index'));
	        }
	    }
	    $this->render('changePassword',array('model'=>$model));
	}
	
	/**
	 * Action for admin to change any user's password
	 * If successful, the browser will be redirected to user update page.
	 * @param int $id the id of the user to change password.
	 */
	public function actionChangeUserPassword($id)
	{
		$model=$this->loadModel($id);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			$model->password=hash('sha512', $model->username.$model->password);
			if($model->save())
				$this->redirect(array('update','id'=>$id));
		}

		$model->password='';//do not need to display old password.
		$this->render('changeUserPassword',array(
			'model'=>$model,
		));
	}

	/**
	 * Performs the AJAX validation. The result will appear on the page.
	 * @param User the objecct to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
